Step 5: Hello Express

ExpressJS (or simply Express) is a web framework for Node. It facilitates building web servers and APIs. We are going to work with Express for several lectures.

Create a new folder, hello-express, and initialize a Node package in it:

yarn init -y

Next, install Express.

yarn add express

Next, add the type and scripts to the package.json:

{
  "name": "hello-express",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",  
  "type": "module",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.18.2"
  }
}

Add a server.js file:

import express from "express";

const port = 3000;
const app = express();

app.get("/", (req, res) => {
  res.send("Hello Express");
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Run the server with yarn start. The app must behave exactly as what we built earlier with the Node’s HTTP module.

Recall: to stop the app, you must halt the process by pressing Ctrl + C.

Let's explore the code:

  • The imported function express exported returns an object we capture in the app variable by invoking express().
  • The app object has methods for handling HTTP requests, among other things.
  • The app.get() handles an HTTP Get request.
  • The first argument to app.get() is the path or API endpoint address.
  • The second argument to app.get() is a callback function. This function is called every time client visits the API endpoint.
  • The call-back function receives two arguments. The req and resp bindings are objects representing the incoming and outgoing data.
  • The app.listen() binds and listens for connections on the specified port. This method is identical to Node's http.Server.listen(). It optionally takes a second argument, a call-back function, which I've used to simply print a message to the terminal.

Express is built on top of Node's HTTP module, but it adds a ton of additional functionality to it. Express provides a clean interface to build HTTP server applications. It offers many utilities, takes care of nuances under the hood, and allows for many other packages to be added as middleware to further the functionality of Express and your server application.